package clients;

import message.Message;
import server.MessageServer;

import java.util.UUID;

/**
 * 客户端
 */
public abstract class MessageClient {

    protected final String id;

    protected String type;

    protected MessageServer server;


    protected MessageClient() {
        this.id = UUID.randomUUID().toString();
    }

    public String getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public void join(MessageServer server) {
        this.server = server;
        server.join(this);
    }

    public void sendMessage(String content) {
        Message message = new Message(this.getId(), content);
        server.sendMessage(message);
    }

    public abstract void sendMessage(Message message);



    public boolean receiveMessage(Message message) {
        String content = message.getContent();
        if (this.getId().equals(message.getSourceId())) {
            return false;
        }
        System.out.println(this.getType() + "端收到消息：" + content);
        return this.receiveHandler(message);
    }

    public abstract boolean receiveHandler(Message message);

    @Override
    public String toString() {
        return "MessageClient{" +
                "type='" + getType() + '\'' +
                ", id='" + getId() + '\'' +
                '}';
    }
}
